import { OperLog } from '@/models/system';
import { Op } from 'sequelize';
import DateUtil from "@/utils/javaScript/date.util";
import { getLogger } from '@/utils/logger';

const logger = getLogger("operLog-service", {
  console: false,
});
const consoleLogger = getLogger("operLog-service");

/**
 * 操作日志服务
 */
class OperLogService {
  /**
   * 新增操作日志
   * @param operLog 操作日志对象
   */
  public async insertOperlog(operLog: any): Promise<void> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`新增操作日志: title=${operLog.title}, operName=${operLog.operName}`);
      
      // 如果没有设置操作时间，设置为当前时间
      if (!operLog.operTime) {
        operLog.operTime = new Date();
      }
      
      const result = await OperLog.create(operLog);
      
      // 记录操作结果
      logger.info(`操作日志新增成功: operId=${result.operId}, title=${operLog.title}`);
    } catch (error) {
      consoleLogger.error(`新增操作日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('新增操作日志失败');
    }
  }

  /**
   * 查询系统操作日志集合
   * @param operLog 操作日志对象
   * @returns 操作日志集合
   */
  public async selectOperLogList(operLog: any, page: number = 1, pageSize: number = 10): Promise<{rows: OperLog[], total: number}> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`查询操作日志列表: ${JSON.stringify(operLog)}, page=${page}, pageSize=${pageSize}`);
      
      const condition: any = {};
      
      // 构建查询条件
      if (operLog.title) {
        condition.title = { [Op.like]: `%${operLog.title}%` };
      }
      
      if (operLog.businessType !== undefined && operLog.businessType !== null) {
        condition.businessType = operLog.businessType;
      }
      
      if (operLog.businessTypes && operLog.businessTypes.length > 0) {
        condition.businessType = { [Op.in]: operLog.businessTypes };
      }
      
      if (operLog.status !== undefined && operLog.status !== null) {
        condition.status = operLog.status;
      }
      
      if (operLog.operName) {
        condition.operName = { [Op.like]: `%${operLog.operName}%` };
      }
      
      if (operLog.operIp) {
        condition.operIp = { [Op.like]: `%${operLog.operIp}%` };
      }

      // 时间范围查询
      if (operLog.params && operLog.params.beginTime && operLog.params.endTime) {
        const beginDate = DateUtil.parseDate(operLog.params.beginTime);
        const endDate = DateUtil.parseDate(operLog.params.endTime);
        
        if (beginDate && endDate) {
          // 设置结束日期为当天的23:59:59
          endDate.setHours(23, 59, 59);
          
          condition.operTime = { 
            [Op.between]: [beginDate, endDate] 
          };
          
          logger.debug(`设置时间范围查询: ${beginDate.toISOString()} 至 ${endDate.toISOString()}`);
        }
      }

      // 分页查询
      const { count, rows } = await OperLog.findAndCountAll({
        where: condition,
        order: [['operId', 'DESC']],
        limit: pageSize,
        offset: (page - 1) * pageSize
      });
      
      // 记录查询结果
      logger.info(`操作日志查询完成: 总数=${count}, 当前页=${page}, 每页大小=${pageSize}`);
      
      return { rows, total: count };
    } catch (error) {
      consoleLogger.error(`查询操作日志列表失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('查询操作日志列表失败');
    }
  }

  /**
   * 批量删除系统操作日志
   * @param operIds 需要删除的操作日志ID
   * @returns 结果
   */
  public async deleteOperLogByIds(operIds: number[]): Promise<number> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`批量删除操作日志: operIds=${JSON.stringify(operIds)}`);
      
      if (!operIds || operIds.length === 0) {
        consoleLogger.error('批量删除操作日志失败: 参数为空');
        throw new Error('操作日志ID不能为空');
      }
      
      const result = await OperLog.destroy({
        where: {
          operId: {
            [Op.in]: operIds
          }
        }
      });
      
      // 记录操作结果
      logger.info(`操作日志批量删除完成: 删除项数量=${operIds.length}, 影响行数=${result}`);
      
      return result;
    } catch (error) {
      consoleLogger.error(`批量删除操作日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('批量删除操作日志失败');
    }
  }

  /**
   * 查询操作日志详细
   * @param operId 操作ID
   * @returns 操作日志对象
   */
  public async selectOperLogById(operId: number): Promise<OperLog | null> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`根据ID查询操作日志: operId=${operId}`);
      
      // 检查operId是否有效
      if (isNaN(operId)) {
        consoleLogger.error(`根据ID查询操作日志失败: operId "${operId}" 不是有效的数字`);
        throw new Error('无效的操作日志ID');
      }
      
      const operLog = await OperLog.findByPk(operId);
      
      // 记录查询结果
      if (operLog) {
        logger.info(`操作日志查询成功: operId=${operId}, title=${operLog.title}`);
      } else {
        logger.info(`未找到操作日志: operId=${operId}`);
      }
      
      return operLog;
    } catch (error) {
      consoleLogger.error(`根据ID查询操作日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('查询操作日志详细信息失败');
    }
  }

  /**
   * 清空操作日志
   */
  public async cleanOperLog(): Promise<void> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info('清空操作日志');
      
      await OperLog.destroy({
        where: {},
        truncate: true
      });
      
      // 记录操作结果
      logger.info('操作日志清空完成');
    } catch (error) {
      consoleLogger.error(`清空操作日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('清空操作日志失败');
    }
  }
}

export default new OperLogService(); 